import datetime
import json
import time
from logger import logger
from msg_manager import MsgManager
from wxmsg_watcher import WxMsgWatcher

wx_msgs_queue_name = 'wx_msgs_queue'


def tasks_watcher():

    watcher = WxMsgWatcher()
    for msg_obj in watcher.new_msgs():
        logger.debug(f'got new msg: {json.dumps(msg_obj, ensure_ascii=False)}')
      
        msg = msg_obj['msg']
        msg_manager = MsgManager(wx_msgs_queue_name)
        msg_manager.send_msg(json.dumps({
            'msg_type': 'KTT',
            'content': msg,
            'msg_time_at': msg_obj['msg_time'],
            'from_user': msg_obj['from_user'],
            'task_time_at': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }, ensure_ascii=False))

        time.sleep(2)
        msg_manager.close()


def main():
    while 1: 
        try:
            tasks_watcher()
        except Exception as e:
            logger.error(f'error导致自动重启: {e}')
            time.sleep(10)

if __name__ == '__main__':
    main()
